package com.redare.dev.smart.generator.workbench.controller;

import com.google.common.collect.ImmutableMap;
import com.redare.devframework.common.pojo.CommonResult;
import com.redare.devframework.webplatform.sdk.core.PlatformSdk;
import com.redare.devframework.webplatform.sdk.core.arg.PlatformArg;
import com.redare.devframework.webplatform.sdk.core.pojo.User;
import com.redare.devframework.webplatform.workbench.conf.WorkbenchConf;
import com.redare.devframework.webplatform.workbench.conf.api.IUrlSignature;
import com.redare.devframework.webplatform.workbench.controller.BaseController;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author yangqy on 2021/11/4
 * @date 2021/11/4 下午2:45
 */
@Controller("com.redare.dev.smart.generator.admin.controller.RootWebController")
public final class RootWebController extends BaseController implements WorkbenchConf {
    private final String WORK_BENCH_PATH = "smart-generator-root";
    @Autowired
    PlatformSdk platformSdk;
    @Autowired(
            required = false
    )
    List<WorkbenchConf> workbenchConfList;
    @Autowired(
            required = false
    )
    IUrlSignature signature;

    public RootWebController() {
    }

    @ResponseBody
    @RequestMapping(
            value = {"/_generator/**"},
            method = {RequestMethod.GET}
    )
    public CommonResult<Void> index(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String contextPath = request.getServletContext().getContextPath();
        String servletPath = request.getServletPath();
        String matchPath = (String)request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        String matchPattern = (String)request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        AntPathMatcher apm = new AntPathMatcher();
        String path = apm.extractPathWithinPattern(matchPattern, matchPath);
        String extName = FilenameUtils.getExtension(path);
        ClassLoader classLoader;
        if (StringUtils.isNotBlank(extName)) {
            classLoader = Thread.currentThread().getContextClassLoader();
            long modifyTime = 0L;

            InputStream inputStream;
            try {
                inputStream = classLoader.getResourceAsStream(String.format("%s/.build_time", "smart-generator-root"));
                if (inputStream != null) {
                    List<String> lines = IOUtils.readLines(inputStream, "UTF-8");
                    if (CollectionUtils.isNotEmpty(lines)) {
                        modifyTime = NumberUtils.toLong((String)lines.get(0), 0L);
                    }
                }
            } catch (Exception var17) {
            }

            inputStream = classLoader.getResourceAsStream(String.format("%s/%s", "smart-generator-root", path));
            if (inputStream == null) {
                return null;
            } else if (this.resource304(modifyTime, request, response)) {
                return null;
            } else {
                if ("css".equalsIgnoreCase(extName)) {
                    response.setHeader("Cache-Control", "public,max-age=31536000");
                    response.setContentType("text/css");
                } else if (!"png".equalsIgnoreCase(extName) && !"jpg".equalsIgnoreCase(extName) && !"jpeg".equalsIgnoreCase(extName)) {
                    if ("js".equalsIgnoreCase(extName)) {
                        response.setHeader("Cache-Control", "public,max-age=31536000");
                        response.setContentType("content-type: application/x-javascript");
                    } else if ("ico".equalsIgnoreCase(extName)) {
                        response.setContentType("image/*");
                    }
                } else {
                    response.setContentType("image/*");
                }

                if (modifyTime > 0L) {
                    response.addHeader("Last-Modified", String.valueOf(modifyTime));
                }

                this.writeFile(inputStream, response);
                return null;
            }
        } else {
            if (!path.endsWith("login") && !path.endsWith("login/") && request.getSession().getAttribute("ROOT_CONF_USER") == null) {
                User user = (User)request.getSession().getAttribute("WEB_WORKBENCH_LOGIN_USER_INFO");
                if (user == null || user.getId() != 0L || !user.isRoot()) {
                    List<String> url = new ArrayList();
                    url.add(contextPath);
                    url.add(servletPath);
                    url.add("_rootlab");
                    url.add("login");
                    response.sendRedirect(String.format("/%s", StringUtils.join(StringUtils.split(StringUtils.join(url, "/"), "/"), "/")));
                    return null;
                }
            }

            classLoader = Thread.currentThread().getContextClassLoader();
            InputStream inputStream = classLoader.getResourceAsStream(String.format("%s/index.html", "smart-generator-root"));
            if (inputStream == null) {
                return null;
            } else {
                List<String> lines = IOUtils.readLines(inputStream, "UTF-8");
                String content = StringUtils.join(lines, "");
                List<String> ctx = new ArrayList();
                if (StringUtils.isNotBlank(contextPath)) {
                    ctx.addAll(Arrays.asList(StringUtils.split(contextPath, "/")));
                }

                if (StringUtils.isNotBlank(servletPath)) {
                    ctx.addAll(Arrays.asList(StringUtils.split(servletPath, "/")));
                }

                String CTX = ctx.isEmpty() ? "" : String.format("/%s", StringUtils.join(ctx, "/"));
                String key = "";
                if (this.signature != null) {
                    key = String.format("%s%s%s", RandomStringUtils.randomAlphanumeric(5), this.signature.getKey(), RandomStringUtils.randomAlphanumeric(6));
                }

                this.writerHtmlToBody(response, velocityEvaluate(content, ImmutableMap.of("CTX", CTX, "CTX_API", CTX, "CTX_API_KEY", key, "CTX_RES", "")));
                return null;
            }
        }
    }

    @ResponseBody
    @RequestMapping(
            value = {"/api/_generator_api/login"},
            method = {RequestMethod.POST}
    )
    public CommonResult<Void> login(@RequestParam(value = "account",required = false) String account, @RequestParam(value = "pwd",required = false) String pwd, HttpServletRequest request) {
        if (!"root".equalsIgnoreCase(account)) {
            return this.returnFailsWrapper("账号或密码错误");
        } else {
            CommonResult<User> result = this.platformSdk.loginPlatform((new PlatformArg.Login()).setAccount(account).setPwd(pwd));
            if (result.isNotSuccess()) {
                return CommonResult.returnFailsWrapper(result.getMessage());
            } else {
                User user = (User)result.getData();
                if (user.getId() != 0L) {
                    return this.returnFailsWrapper("账号或密码错误");
                } else {
                    request.getSession().setAttribute("ROOT_CONF_USER", user);
                    return this.returnSuccessWrapper();
                }
            }
        }
    }

    @ResponseBody
    @RequestMapping(
            value = {"/api/_generator_api/loginOut"},
            method = {RequestMethod.POST}
    )
    public CommonResult<Void> loginOut(HttpServletRequest request) {
        request.getSession().removeAttribute("ROOT_CONF_USER");
        request.getSession().invalidate();
        return this.returnSuccessWrapper();
    }

}
